<template>
  <div class="app-container">
    <div class="card-container">
      <el-card>
        <div slot="header">
          <span>{{ pageTitle }}</span>
        </div>
        
        <el-form 
          ref="formRef" 
          :model="form" 
          :rules="rules" 
          label-width="80px"
          :disabled="isDetail"
        >
          <el-form-item label="博客标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入博客标题" />
          </el-form-item>
          <el-form-item label="URL友好标识" prop="slug">
            <el-input v-model="form.slug" placeholder="请输入URL友好标识" />
          </el-form-item>
          <el-form-item label="博客导语/摘要" prop="excerpt">
            <el-input v-model="form.excerpt" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="博客正文" prop="content" v-if="!isDetail">
            <QuillEditor
              v-model:content="form.content"
              :options="editorOptions"
              height="500px"
            />
          </el-form-item>
          <el-form-item label="博客正文" v-if="isDetail">
            <div v-html="form.content" class="blog-content"></div>
          </el-form-item>
          <el-form-item label="封面" prop="coverImageUrl">
            <image-upload v-model="form.coverImageUrl" :disabled="isDetail"/>
          </el-form-item>
          <el-form-item label="发布状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in ver_blog_status"
                :key="dict.value"
                :label="parseInt(dict.value)"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item v-if="!isDetail">
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="cancel">取消</el-button>
          </el-form-item>
          <el-form-item v-if="isDetail">
            <el-button @click="cancel">返回</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup name="VerBlogEdit">
import { getVerBlog, addVerBlog, updateVerBlog } from "@/api/system/verBlog";
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { useRoute, useRouter } from 'vue-router';
import { onMounted, getCurrentInstance, reactive, ref, toRefs, computed } from 'vue';

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const { ver_blog_status } = proxy.useDict('ver_blog_status');
const formRef = ref(null);

// 判断页面类型：新增/编辑/详情
const actionType = computed(() => route.params.action);
const blogId = computed(() => route.params.id);
const isDetail = computed(() => actionType.value === 'detail');
const isAdd = computed(() => actionType.value === 'add');
const isEdit = computed(() => actionType.value === 'edit');

// 页面标题
const pageTitle = computed(() => {
  if (isAdd.value) return '新增博客';
  if (isEdit.value) return '编辑博客';
  if (isDetail.value) return '博客详情';
  return '博客管理';
});

// 表单数据与校验规则
const data = reactive({
  form: {
    blogId: null,
    title: null,
    slug: null,
    excerpt: null,
    content: null,
    coverImageUrl: null,
    authorId: null,
    authorName: null,
    categoryId: null,
    status: 0, // 默认未发布
    viewCount: 0,
    publishTime: null,
    createTime: null,
    updateTime: null
  },
  rules: {
    title: [{ required: true, message: "博客标题不能为空", trigger: "blur" }],
    slug: [{ required: true, message: "URL友好标识不能为空", trigger: "blur" }],
    content: [{ required: true, message: "博客正文不能为空", trigger: "blur" }],
    status: [{ required: true, message: "发布状态不能为空", trigger: "change" }]
  }
});
const { form, rules } = toRefs(data);

// 富文本编辑器配置
const editorOptions = {
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'align': [] }],
      ['link', 'image']
    ]
  }
};

/** 加载博客数据 */
function loadBlogData(id) {
  getVerBlog(id).then(response => {
    form.value = response.data;
  }).catch(err => {
    proxy.$modal.msgError('加载数据失败');
    router.push('/system/ver-blog');
  });
}

/** 提交表单 */
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {
        addVerBlog(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          router.push('/system/ver-blog');
        });
      } else {
        updateVerBlog(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          router.push('/system/ver-blog');
        });
      }
    }
  });
}

/** 取消/返回 */
function cancel() {
  router.push('/system/ver-blog');
}

// 页面初始化
onMounted(() => {
  // 编辑或详情页面需要加载数据
  if (isEdit.value || isDetail.value) {
    if (blogId.value) {
      loadBlogData(blogId.value);
    } else {
      proxy.$modal.msgError('参数错误');
      router.push('/system/ver-blog');
    }
  }
});
</script>

<style scoped>
.card-container {
  padding: 16px;
  background-color: #fff;
  min-height: calc(100vh - 130px);
}

.blog-content {
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 16px;
  min-height: 500px;
  line-height: 1.8;
}

.blog-content img {
  max-width: 100%;
  margin: 10px 0;
}
</style>
